//
//  User.m
//  极致荟
//
//  Created by mac on 14-4-17.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "User.h"

@implementation User

static int maptimeindex;
+ (User *)defuceUser
{
    static User *user;
    if(!user)
    {
        maptimeindex=0;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            user=[[User alloc]init];
            
        });
    }
    return user;
}

///获取用户当前城市

- (void)userCity
{
    
    NSString *path=NSHomeDirectory();
    path=  [path stringByAppendingString:@"/Documents/CityList.plist"];
    NSDictionary *citypilst=[[NSDictionary alloc] initWithContentsOfFile:path];
    self.citydic=[citypilst objectForKey:@"Dcity"];
    if(![CLLocationManager locationServicesEnabled ])
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            UIAlertView *aler=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前定位服务未打开，请在设置中打开定位服务" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil] ;
            [aler show];
        });
        
        
        if(timer)
        {
            [timer invalidate];
            timer=nil;
        }
        
        
    }else
    {
        //开启发送循环，向服务器发送用户坐标
        timer=nil;
        timer=[NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(locatuser:) userInfo:nil repeats:YES];
    }
    
    
    
    [HttpRequest httpRequestPost:JZHHTTPURL(@"index/cityList") parameters:nil block:^(id data, HttpReturnCode rerurncode) {
        _locationmanager =[[CLLocationManager alloc]init];
        [_locationmanager setDelegate:self];
        [_locationmanager startUpdatingLocation];
        if(rerurncode==HTTPReturnCodeSuccess)
        {
            citydata=data;
            [self writePlist:nil];
        }
    }];
}

///写入城市列表到plist文件
- (void)writePlist:(NSDictionary *)dcity
{
    NSString *path=NSHomeDirectory();
    path=  [path stringByAppendingString:@"/Documents/CityList.plist"];
    NSMutableDictionary *cityPlist=[[NSMutableDictionary alloc]init];
    NSDictionary *citylist;
    NSDictionary *dic=citydata;
    citylist=[[dic objectForKey:@"data"] objectForKey:@"cityList"];
    [cityPlist setObject:citylist forKey:@"City"];
    if(dcity)
    {
        [cityPlist setObject:dcity forKey:@"Dcity"];
    }
    if([cityPlist writeToFile:path  atomically:YES])
    {
        NSLog(@"城市列表以保存成功~~");
    }else
    {
        NSLog(@"完蛋了，城市列表保存失败-……-'");
    }


}
#pragma mark----定位代理-----
- (void)locationManager:(CLLocationManager *)manager
	 didUpdateLocations:(NSArray *)locations
{
  
    //获取当前所在城市名称
    CLLocation *userLocathion=[manager location];
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
    if(maptimeindex==0)
    {
        //向服务器发送坐标系
        [self locationHttp:manager];
        maptimeindex=1;
    }
   
    [geoCoder reverseGeocodeLocation:userLocathion completionHandler:^(NSArray *placemarks, NSError *error) {
        NSString *dcitryname=@"";
        for (CLPlacemark * placemark in placemarks)
        {
            NSDictionary *dic=[placemark addressDictionary];
            dcitryname=[dic objectForKey:@"State"] ;
        }
        
        //数据解析
        NSDictionary *citylist;
        NSDictionary *dic=citydata;
        citylist=[[dic objectForKey:@"data"] objectForKey:@"cityList"];
        
        //获取当前城市的ID
        if(![dcitryname isEqualToString:@""] && !self.citydic)
        {
            
            for(NSString *str in [citylist allValues])
            {
               
                if([str isEqualToString:[dcitryname substringToIndex:dcitryname.length-1]])
                {
                    NSDictionary *dcity=[[NSDictionary alloc]initWithObjectsAndKeys:str,@"name",[citylist allKeysForObject:str][0],@"id" ,nil];
                    self.citydic=dcity;
                    [self writePlist:dcity];
                    
                    break ;
                }else if([str isEqualToString:dcitryname])
                {
                    NSDictionary *dcity=[[NSDictionary alloc]initWithObjectsAndKeys:str,@"name",[citylist allKeysForObject:str][0],@"id" ,nil];
                    [self writePlist:dcity];
                    self.citydic=dcity;
                    break;
                }
            }
            
        }
        
        //停止使用定位服务
        [manager stopUpdatingLocation];
        
    }];
}

- (void)locationHttp:(CLLocationManager *)managr
{
    NSLog(@"%f",managr.location.coordinate.longitude);
    NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithDouble:managr.location.coordinate.latitude],@"coordX",[NSNumber numberWithDouble:managr.location.coordinate.longitude],@"coordY", [NSNumber numberWithInt:self.userId],@"userId", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"member/updateCoord") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            NSLog(@"%@",data);
        }
    }];
}

///返回最后登录时间字符串
- (NSString *)lastLoginTime:(NSDate *)date
{
    NSDate *ddate=[NSDate date];
    long timerc=[ddate timeIntervalSince1970]-[date timeIntervalSince1970];
    int tian=0;
    int shi=0;
    int feng=0;
    feng=timerc/60;
    shi=feng/60;
    tian=shi/24;
    if(tian!=0)
    {
        return [NSString stringWithFormat:@"%d天前",tian];
    }
    
    if(shi!=0)
    {
        return [NSString stringWithFormat:@"%d小时前",shi];
    }
    
    if(feng==0)
    {
        return [NSString stringWithFormat:@"%d分钟前",1];

    }else
    {
        return  [NSString stringWithFormat:@"%d分钟前",feng];
    }
    
}
- (void)locatuser:(NSTimer *)timer
{
    maptimeindex=0;
    [self.locationmanager startUpdatingLocation];
}
- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    
    NSString *errorString;
    [manager stopUpdatingLocation];
    NSLog(@"Error: %@",[error localizedDescription]);
    switch([error code]) {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"Access to Location Services denied by user";
            //Do something...
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"Location data unavailable";
            //Do something else...
            break;
        default:
            errorString = @"An unknown error has occurred";
            break;
    }
   
}
@end
